<template>
	<view style="height: 100%;">
		<!-- 正文 -->
		<view v-if="!networkStatus">
			<nonetword @onclick="getList"></nonetword>
		</view>
		<view v-if="networkStatus" style="height: 100%;">
			

			<!-- 推广弹框 -->
			<!-- <cover-view>
				<button class="save-btn" type="primary"  @tap.prevent.stop="saveImage()">保存图片</button>
			</cover-view> -->

			<view class="flex_row_c_c modalView" :class="qrShow?'show':''" @tap="hideQr()">
				<view class="flex_column">
					<view class="backgroundColor-white padding1vh border_radius_10px">
						<image v-if="poster.finalPath" :src="poster.finalPath" mode="widthFix" class="posterImage"></image>
					</view>
					<view class="flex_row marginTop2vh">
						<!-- <button class="save-btn" type="primary"  @tap.prevent.stop="saveImage()">保存图片</button> -->

						<!-- <button type="primary" size="mini" @tap.prevent.stop="share()">分享图片</button> -->
					</view>
				</view>
			</view>
			<view class="hideCanvasView"  style=" z-index:999999999999999 !important;">
				<!-- :style="{top:isSet ? 0 : statusBarHeight}" -->
				<canvas class="hideCanvas" canvas-id="default_PosterCanvasId" style="width:750rpx;height:1334rpx;position: absolute; z-index:99999999999999999999999 !important;">
					
					<cover-view>
						
							<button v-if="isSet"  class="save-btn" type="primary" @tap.prevent.stop="saveImage()">
								保存图片
							</button>
							<button  @tap.prevent.stop="setFun()" v-else type="primary" class="set-btn"  open-type="openSetting" bindopensetting="callback">
								允许访问相册
							</button>
							
						
						
					</cover-view>
					<!-- :style="{width: (poster.width||0) + 'px', height: (poster.height||0) + 'px'}" -->
				</canvas>
				
			</view>
			
			<!-- <view class="home-box">
				首页
			</view> -->
			<view style="z-index: 99999999999999;">
				<button v-if="isSet"  class="save-btn" type="primary" @tap.prevent.stop="saveImage()" style=" left: 180rpx;background-color:#69A4FE !important;">
					保存图片
				</button>
				<button  @tap.prevent.stop="setFun()" v-else type="primary" class="set-btn"  open-type="openSetting" bindopensetting="callback">
					允许访问相册
				</button>
			</view>
			<view style="height: 50rpx;"></view>

			<!-- 登录弹框 -->
			<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
		</view>
	</view>
</template>
<script>
	import {oss_host} from '@/config/config.js';	
	// 推广名片
	import _app from '@/js_sdk/QuShe-SharerPoster/util/QS-SharePoster/app.js';
	import {
		getSharePoster
	} from '@/js_sdk/QuShe-SharerPoster/util/QS-SharePoster/QS-SharePoster.js';
	import he from '@/utils/he.js'
	//公共底部组件引入
	import {
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
				statusBarHeight:'',
				isSet:true,
				isTop: 0,
				heightVal: '-112rpx',
				//网络状态
				networkStatus: true,
				skeletonShow: true,
				fixedTop: 140,

				//接口数据
				data: {
					//客服电话
					serviceMobile: '18677057271',
					//个人信息,
					userInfo: {
						nickname: '游客',
						face: '',
						signature: '点击昵称跳转登录/注册页',
						integral: 0,
						balance: 0,
						envelope: 0,
						exp: 0,
						upExp: 0,
						vipname: ''
					},

				},
				headerPosition: "fixed",
				headerTop: null,
				statusTop: null,
				showHeader: true,
				// 推广名片
				hasLogin: false,
				poster: {},
				qrShow: false,
				canvasId: 'default_PosterCanvasId',

				modal: false,
				//确认弹框
				modalButton: [{
					text: "取消",
					type: 'gray'
				}, {
					text: "确定"
				}],
				qrUrl: '',
				bargain_id:'',//砍价id
				product:'',
				id:'',
				product_name:'',
				cover_image:'',
				price:'',
				cost:'',
				// 节点
				//生成二维码地址
				qrImgHost: '',
				appWidth: null,
				appHeight: null,
				OSS_HOST: oss_host,
				rate: 0,
				// OSS_HOST:'../../static/',

			}
		},
		components: {


		},
		computed: {
			...mapGetters(['netWorkType', 'loginStatus']),
			expup: function() {
				return parseInt(this.data.userInfo.exp / this.data.userInfo.upExp * 100)
			}
		},
		onPageScroll: function(e) {

			if (e.scrollTop > 100) {
				this.isTop = 1
			} else {
				this.isTop = 0
			}
		},
		//下拉刷新，需要自己在page.json文件中配置开启页面下拉刷新 "enablePullDownRefresh": true
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onPageScroll(e) {
			//兼容iOS端下拉时顶部漂移
			this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
			this.headerTop = e.scrollTop >= 0 ? null : 0;
			this.statusTop = e.scrollTop >= 0 ? null : -this.statusHeight + 'px';
		},
		onLoad(e) {
			if(typeof  e.id !=undefined){
				this.id = e.id||0
			}			
			
			
			let _this = this;
			this.GetStatusBarHeight()
			uni.getSystemInfo({
				success: function(res) {
					_this.appWidth = res.windowWidth;
					// _this.appHeight = res.windowHeight;
					_this.appHeight = res.windowHeight - 88;
					_this.rate = 0.5625 - parseFloat(_this.appWidth / _this.appHeight);
					console.log('kkkkkk');
					console.log(parseFloat(_this.appWidth / _this.appHeight))
					console.log(_this.rate)
					console.log(_this.appWidth)
					console.log(_this.appHeight)
					_this.$nextTick(function() {
						_this.getDetail();

					})
					
				}
			});
			this.statusHeight = 0;
			// #ifdef APP-PLUS
			this.showHeader = false;
			this.statusHeight = plus.navigator.getStatusbarHeight();
			// #endif
			if (!this.loginStatus) {
				store.dispatch('changeLogin', false)
			}
			this.qrImgHost = this.$service.getQrImgHost()
			//获取满屏高度




		},
		onReady() {

		},
		// //2.分享到朋友圈
		// onShareTimeline(res) {
		// 	const _this = this;
			
		// 	const shareTitle = 'OPPORT瓯品医械商城'
		// 	const shareText =_this.data.detail.name
		//     return {
		//         title: shareTitle,
		//         path: `/pages/home/home?user_id=${_this.id}`,
		//         imageUrl:  _this.data.detail.cover_image,
		//     } 
		// },
		onShow: function() {
			let _this = this;

			this.qrShow = true;
			// this.heightVal='-'+(140+44-uni.getSystemInfoSync().statusBarHeight)+ 'px';
			// #ifdef MP-WEIXIN
			if (wx.hideHomeButton) {
				wx.hideHomeButton();
			}
			// #endif

			// this.$nextTick(function() {
			// 	_this.appWidth =375;
			// 	_this.appHeight =872;
			// 	_this.shareFc();

			// })
			// poster.finalPath
		},
		filters: {
			iconFilters: function(x) {
				return he.decode(x);
			}
		},
		methods: {
			GetStatusBarHeight() {
				let that = this;
				wx.getSystemInfo({
					success: function(res) {
						that.statusBarHeight=(res.statusBarHeight+55)+'px'; //这就是状态栏的高度
						
					},
				});
			},

			// 推广名片
			shareFc() {
				let _this = this;
				
				var opt = {
					url: '/user/userInfo',
					data: {

					},
					success: function(res) {

						if (res.status == 1) {
							_this.data.userInfo =res.data.userInfo
							console.log(_this.cover_image,_this.product_name,_this.price,_this.cost)
							// res.data.userInfo.avatar = 'http://app.aiouning.com/uploader/upload/202302/23/2023022310333763f6d081310df.png'
							_this.createImg(res.data.userInfo.id, res.data.userInfo.nickname, res.data.userInfo.avatar)
						} else {
							uni.showToast({
								icon: 'none',
								title: res.message
							});
						}
					}
				};

				_this.$service.GetApi(opt);
			},
			getDetail(){
				const _this = this
				
				var opt = {
					url: '/product/detail', 
					data:{
						id:_this.id||'',
						// shape_code:_this.code||''
						
					},
					success: function(res) { 
					 
						if (res.status == 1) { 
							 let result = res.data
							
							_this.product =result.detail
							_this.shareFc()
							
							
						}  else{
							uni.showToast({
								icon:'none',
								title:'无此产品信息'
							})
							setTimeout(function () {
								
								 _this.onBack()
								
							}, 3000);
							
							
							
						}
						// _this.skeletonShow = false;
					}
				};
						
				
				this.$service.GetApi(opt) //网络
			},
			async createImg(uid, nickname, avatar) {
				let _this = this;
				// console.log(this.product)
				// const product = JSON.parse(this.product)
				
				console.log(_this.product)
				try {
					//console.log('准备生成:' + new Date())
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'server',
						posterCanvasId: this.canvasId, //canvasId
						delayTimeScale:50, //延时系数
						drawDelayTime:1000, //额外延时时长, 生成白图时调大此参数
						backgroundImage: _this.OSS_HOST + 'img/goods-share-bg.png',
						// backgroundColor:'#ccc',
						background: {
							width: 360,
							heght: 1334,
							backgroundColor: '#666'
						},
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							console.log(bgObj)
							bgObj.width = _this.appWidth; //cj
							bgObj.height = 1334 * _this.appWidth / 750
							const dx = bgObj.width * 0.45;
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							const name =_this.product.name;
							const cover_image = _this.product.cover_image;
							const price =_this.product.price;
							const cost  = _this.product.cost;

							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([
									
									{
										type: 'image',
										url: avatar,
										alpha: 1,
										dx:  bgObj.width * 0.52,
										dy: bgObj.height*0.04,
										correctLevel: 0,
										infoCallBack(imageInfo) {
											let scale = bgObj.width * 0.1 / imageInfo.height;
											return {
												circleSet: {
													x: imageInfo.width * scale / 2,
													y: bgObj.width * 0.1 / 2,
													r: bgObj.width * 0.1 / 2
												}, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
												dWidth: imageInfo.width * scale, // 因为设置了圆形图片 所以要乘以2
												dHeight: bgObj.width * 0.1,
												/* roundRectSet: { // 圆角矩形
													r: imageInfo.width * .1
												} */
											}
										}
									},
									{
										type: 'text',
										fontStyle: 'italic',
										text: nickname,
										size: 14,
										color: '#000',
										alpha: 1,
										lineFeed: {
											maxWidth: 80,
											lineHeight: 25,

											lineNum: -1,
											dx: -1
										},
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.63,
												dy: bgObj.height*0.055,
											}
										},
										serialNum: 0,
										id: 'tag1' //自定义标识
									},
									{
										type: 'text',
										fontStyle: 'italic',
										text: '都是值得买的好货',
										size: 12,
										color: '#888',
										
										alpha: 1,
										lineFeed: {
											maxWidth: 100,
											lineHeight: 25,
											// overflow: hidden,
											lineNum: -1,
											dx: -1
										},
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.63,
												dy: bgObj.height*0.08,
											}
										},
										serialNum: 0,
										// id: 'tag1' //自定义标识
									},
									{
										type: 'image',
										url: cover_image,
										alpha: 1,
										dx:  bgObj.width * 0.063,
										dy: bgObj.height*0.128,
										correctLevel: 0,
										infoCallBack(imageInfo) {
											let scale = bgObj.width * 0.75 / imageInfo.height;
											// console.log('******',scale)
											return {
												// circleSet: {
												// 	x: imageInfo.width * scale / 2,
												// 	y: bgObj.width * 0.75 / 2,
												// 	r: bgObj.width * 0.75 / 2
												// }, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
												dWidth: bgObj.width*0.875, // 因为设置了圆形图片 所以要乘以2
												dHeight: bgObj.width * 0.875,
												// roundRectSet: { // 圆角矩形
												// 	r: imageInfo.width * .1
												// }
											}
										}
									},
									
									{
										type: 'text',
										// fontStyle: 'italic',
										text:name,
										size: 20,
										color: '#333',										
										alpha: 1,
										letterSpacing:1,
										// width:bgObj.width*0.8,
										// weight:'bold',
										font:{
											fontWeight:'bold',
										},
										lineHeight:20,
										lineFeed: {
											maxWidth: bgObj.width * 0.84,
											size:2,
											
											lineNum: 2,//指定显示行数  -1不限制
											dx: -1
										},
										
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.08,
												dy: bgObj.width * 1.16,
											}
										},
										serialNum: 0,
										// id: 'tag2' //自定义标识
									},
									{
										type: 'text',
										// fontStyle: 'italic',
										text:'￥',
										size: 12,
										color: '#FF5733',										
										alpha: 1,
										// width:bgObj.width*0.8,
										// weight:'bold',
										
										lineFeed: {
											maxWidth: 20,
											
											
											lineNum: -1,//指定显示行数  -1不限制
											dx: -1
										},
										
										
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.08,
												dy: bgObj.width * 1.4,
											}
										},
										serialNum: 0,
										// id: 'tag2' //自定义标识
									},
									{
										type: 'text',
										// fontStyle: 'italic',
										text:price,
										size: 24,
										color: '#FF5733',										
										alpha: 1,
										// width:bgObj.width*0.8,
										weight:'bold',
										lineFeed: {
											maxWidth: 150,
											
											
											lineNum: -1,//指定显示行数  -1不限制
											dx: -1
										},
										
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.11,
												dy: bgObj.width * 1.4,
											}
										},
										serialNum: 0,
										// id: 'tag2' //自定义标识
									},
									// {
									// 	type: 'text',
									// 	// fontStyle: 'italic',
									// 	text:'原价：￥'+cost,
									// 	size: 14,
									// 	color: '#888888',										
									// 	alpha: 1,
									// 	// textDecoration:'line-through',
									// 	// width:bgObj.width*0.8,
										
									// 	lineThrough:{
									// 		cap:'butt',
											
									// 		width:'1'
									// 	},
									// 	lineFeed: {
									// 		maxWidth: 150,
									// 		// textDecoration:'line-through',
											
									// 		lineNum: -1,//指定显示行数  -1不限制
									// 		dx: -1
									// 	},
										
									// 	textAlign: 'left',
									// 	textBaseline: 'middle',
									// 	infoCallBack(textLength) {
									// 		//_app.log('index页面的text的infocallback ，textlength:' + textLength);
									// 		return {
									// 			dx:  bgObj.width * 0.1,
									// 			dy: bgObj.width * 1.5,
									// 		}
									// 	},
									// 	serialNum: 0,
									// 	// id: 'tag2' //自定义标识
									// },
									{
										type: 'text',
										// fontStyle: 'italic',
										text:'实际价格以页面页面为准',
										size: 12,
										color: '#888888',										
										alpha: 1,
										// textDecoration:'line-through',
										// width:bgObj.width*0.8,
										
										// lineThrough:{ // 中划线
										// 	cap:'butt',
											
										// 	width:'1'
										// },
										lineFeed: {
											maxWidth: 200,
											// textDecoration:'line-through',
											
											lineNum: -1,//指定显示行数  -1不限制
											dx: -1
										},
										
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.1,
												dy: bgObj.width * 1.65,
											}
										},
										serialNum: 0,
										// id: 'tag2' //自定义标识
									},
									{
										type: 'text',
										// fontStyle: 'italic',
										text:'-长按查看详情-',
										size: 12,
										color: '#888888',										
										alpha: 1,
										// textDecoration:'line-through',
										// width:bgObj.width*0.8,
										
										// lineThrough:{ // 中划线
										// 	cap:'butt',
											
										// 	width:'1'
										// },
										lineFeed: {
											maxWidth: 200,
											// textDecoration:'line-through',
											
											lineNum: -1,//指定显示行数  -1不限制
											dx: -1
										},
										
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx:  bgObj.width * 0.63,
												dy: bgObj.width * 1.65,
											}
										},
										serialNum: 0,
										// id: 'tag2' //自定义标识
									},
									{
										type: 'qrcode',
										text: this.qrImgHost + '/wechat/goodsDetailShare/param/?user_id=' + uid+'&id='+_this.product.id,
										size: bgObj.width * 0.26,
										dx:bgObj.width * 0.63,
										dy: bgObj.width * 1.34,
									}
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					//console.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath)
					this.poster.finalPath = d.poster.tempFilePath;
					this.qrShow = true;
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
					console.log(JSON.stringify(e));
				}
			},
			hideQr() {
				this.qrShow = false;
			},

			// 刷新的方法
			refresh() {
				this.getList();
			},

			toMyQR() {

				const _this = this
				_this.$refer.setVilit('/packageUser/pages/user/myQR/myQR')
				let callback = function(url) {
					_this.$refs.popupvLogin.open()
				}
				_this.$refer.toUrl(callback)
			},

			toLogin() {
				const _this = this
				if (this.loginStatus) {
					return
				}

				let options = {
					msg: '请登陆',
					type: 'danger'
				};
				this.$refs.toast.showTips(options);

				setTimeout(function() {
					// uni.navigateTo({
					// 	url:'../loginer/login/login'
					// })
					_this.$refer.setVilit('/pages/loginer/login/login')
					let callback = function(url) {
						_this.$refs.popupvLogin.open()
					}
					_this.$refer.toUrl(callback)
				}, 2000)

			},
			isLogin() {
				//实际应用中,用户登录状态应该用token等方法去维持登录状态.
				const value = uni.getStorageSync('UserInfo');
				if (value) {
					return true;
				}
				return false
			},
			callback() {
				let _this=this;
				uni.showModal({
					content: '检测到您没打开获取相册功能权限，是否去设置打开？',
					confirmText: "确认",
					cancelText: '取消',
					success: (res) => {
						//_this.isSet=true;

					}
				})
			},
			setFun(){
				let _this=this;
				setTimeout(function(cv){
					_this.isSet=true;
				},3000)
				
			},


			saveImage() {
				let _this = this;
				// #ifndef H5
				uni.getSetting({
					success(res) {

						let result = res.authSetting;
						_this.isSet=result['scope.writePhotosAlbum'];
						if (!result['scope.writePhotosAlbum']) {

							uni.authorize({ //如果没有授权，向用户发起请求
								scope: 'scope.writePhotosAlbum',
								success: () => {
									
								},
								fail: () => {
									
									uni.showToast({
										title: "请打开保存相册权限，再点击保存相册分享",
										icon: "none"
									
									});
									
									// uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
									// 	success: (res2) => {
									// 		console.log(res2.authSetting)
									// 	}
									// });
									
								}
							})
							// uni.showToast({
							// 	title: "请打开保存相册权限，再点击保存相册分享",
							// 	icon: "none"

							// });
							// uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
							// 	success: (res2) => {
							// 		console.log(res2.authSetting)
							// 	}
							// });


						} else {
							uni.saveImageToPhotosAlbum({
								filePath: _this.poster.finalPath,
								success(res) {
									_app.showToast('保存成功');
								}
							})
						}
					}
				})
				// uni.authorize({
				//     scope: 'scope.writePhotosAlbum',
				//     success() {
				//         uni.saveImageToPhotosAlbum({
				//         	filePath: this.poster.finalPath,
				//         	success(res) {
				//         		_app.showToast('保存成功');
				//         	}
				//         })
				//     }
				// })


				// #endif
				// #ifdef H5
				_app.showToast('保存了');
				// #endif
			},
			share() {
				// #ifdef APP-PLUS
				_app.getShare(false, false, 2, '', '', '', this.poster.finalPath, false, false);
				// #endif

				// #ifndef APP-PLUS
				_app.showToast('分享了');
				// #endif
			},
			modalClick(e) {
				const _this = this
				let index = e.index;
				if (index === 0) {
					_this.modalHide()
					return
				}
				uni.setStorageSync('token', '');
				uni.setStorageSync('hasLogin', false);
				let options = {
					msg: '清理成功',
					type: 'green'
				};
				this.$refs.toast.showTips(options);
				_this.modalHide()

			},
			modalHide() {
				this.modal = false
			},

		}
	}
</script>
<style lang="scss">
	@import "./qrcode.scss";
</style>
